package net.xuele.learn.flink.connected;

import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.RichCoFlatMapFunction;
import org.apache.flink.util.Collector;

/**
 * 一个控制流是用来指定哪些词需要从 streamOfWords 里过滤掉的。
 * 一个称为 ControlFunction 的 RichCoFlatMapFunction 作用于连接的流来实现这个功能
 * RichCoFlatMapFunction 是一种可以被用于一对连接流的FlatMapFunction，并且它可以调用rich function的接口。这意味着它可以是有状态的
 */
public class TestConnected {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 需要背过滤掉的单词
        DataStream<String> control = env
                .fromElements("DROP", "IGNORE")
                .keyBy(x -> x);

        DataStream<String> streamOfWords = env
                .fromElements("Apache", "DROP", "Flink", "IGNORE")
                .keyBy(x -> x);

        control
                .connect(streamOfWords)
                .flatMap(new ControlFunction())
                .print();

        env.execute();
    }

    /**
     * flatMap1和flatMap2的执行顺序是不一定的
     */
    static class ControlFunction extends RichCoFlatMapFunction<String, String, String> {

        private static final long serialVersionUID = -2912760580986570577L;
        // 用于记录在数据流 control 中出现过的键，并且这些单词从 streamOfWords 过滤掉
        private ValueState<Boolean> blocked;

        @Override
        public void open(Configuration config) {
            blocked = getRuntimeContext()
                    .getState(new ValueStateDescriptor<>("blocked", Boolean.class));
        }

        /**
         * control 流中的元素会进入 flatMap1
         *
         * @param control_value
         * @param collector
         * @throws Exception
         */
        @Override
        public void flatMap1(String control_value, Collector<String> collector) throws Exception {
            System.out.println("11111111" + control_value);
            blocked.update(Boolean.TRUE);
        }

        /**
         * streamOfWords 中的元素会进入 flatMap2
         * <p>
         * 这是由两个流连接的顺序决定的，本例中为 control.connect(streamOfWords)
         *
         * @param data_value
         * @param collector
         * @throws Exception
         */
        @Override
        public void flatMap2(String data_value, Collector<String> collector) throws Exception {
            System.out.println(2222222 + data_value);
            if (blocked.value() == null) {
                collector.collect(data_value);
            }
        }
    }
}
